package com.demo.youxuanmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.entity.Cart;
import com.demo.youxuanmall.entity.Product;
import com.demo.youxuanmall.mapper.CartMapper;
import com.demo.youxuanmall.service.CartService;
import com.demo.youxuanmall.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    private static final Logger log = LoggerFactory.getLogger(CartServiceImpl.class);

    @Autowired
    private ProductService productService;

    @Override
    @Transactional
    public Result<Cart> addToCart(Long userId, Long productId, Integer quantity) {
        // 参数检查
        if (userId == null || productId == null || quantity == null || quantity <= 0) {
            return Result.error("参数错误");
        }

        // 查询商品是否存在
        Product product = productService.getById(productId);
        if (product == null) {
            return Result.error("商品不存在");
        }

        // 判断商品是否上架
        if (product.getStatus() != 1) {
            return Result.error("商品已下架");
        }

        // 判断库存是否充足
        if (product.getStock() < quantity) {
            return Result.error("库存不足");
        }

        // 查询购物车是否已存在该商品
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, userId)
                .eq(Cart::getProductId, productId);
        Cart existingCart = getOne(queryWrapper);

        if (existingCart != null) {
            // 如果已存在，则更新数量
            int newQuantity = existingCart.getQuantity() + quantity;
            // 再次检查库存是否充足
            if (product.getStock() < newQuantity) {
                return Result.error("库存不足");
            }
            existingCart.setQuantity(newQuantity);
            updateById(existingCart);
            existingCart.setProduct(product);
            return Result.success(existingCart);
        } else {
            // 如果不存在，则新增购物车记录
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setProductId(productId);
            cart.setQuantity(quantity);
            cart.setChecked(1); // 默认选中
            save(cart);
            cart.setProduct(product);
            return Result.success(cart);
        }
    }

    @Override
    public Result<List<Cart>> listUserCarts(Long userId) {
        if (userId == null) {
            return Result.error("参数错误");
        }

        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, userId)
                .orderByDesc(Cart::getUpdateTime);
        List<Cart> cartList = list(queryWrapper);

        // 查询商品信息
        for (Cart cart : cartList) {
            Product product = productService.getById(cart.getProductId());
            cart.setProduct(product);
            cart.setPrice(product.getPrice());  // 设置价格
        }

        return Result.success(cartList);
    }

    @Override
    @Transactional
    public Result<Cart> updateQuantity(Long userId, Long id, Integer quantity) {
        // 参数检查
        if (userId == null || id == null || quantity == null || quantity <= 0) {
            return Result.error("参数错误");
        }

        // 查询购物车记录
        Cart cart = getById(id);
        if (cart == null || !cart.getUserId().equals(userId)) {
            return Result.error("购物车商品不存在");
        }

        // 查询商品是否存在
        Product product = productService.getById(cart.getProductId());
        if (product == null) {
            return Result.error("商品不存在");
        }

        // 判断库存是否充足
        if (product.getStock() < quantity) {
            return Result.error("库存不足");
        }

        // 更新数量
        cart.setQuantity(quantity);
        updateById(cart);
        cart.setProduct(product);

        return Result.success(cart);
    }

    @Override
    @Transactional
    public Result<Cart> updateChecked(Long userId, Long id, Integer checked) {
        // 参数检查
        if (userId == null || id == null || (checked != 0 && checked != 1)) {
            return Result.error("参数错误");
        }

        // 查询购物车记录
        Cart cart = getById(id);
        if (cart == null || !cart.getUserId().equals(userId)) {
            return Result.error("购物车商品不存在");
        }

        // 查询商品信息
        Product product = productService.getById(cart.getProductId());

        // 更新选中状态
        cart.setChecked(checked);
        updateById(cart);
        cart.setProduct(product);

        return Result.success(cart);
    }

    @Override
    @Transactional
    public Result<Void> deleteCart(Long userId, Long id) {
        // 参数检查
        if (userId == null || id == null) {
            return Result.error("参数错误");
        }

        // 查询购物车记录
        Cart cart = getById(id);
        if (cart == null || !cart.getUserId().equals(userId)) {
            return Result.error("购物车商品不存在");
        }

        // 删除购物车记录
        removeById(id);

        return Result.success();
    }

    @Override
    @Transactional
    public Result<Void> selectAllOrNone(Long userId, Integer checked) {
        // 参数检查
        if (userId == null || (checked != 0 && checked != 1)) {
            return Result.error("参数错误");
        }

        // 查询用户所有购物车记录
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, userId);
        List<Cart> cartList = list(queryWrapper);

        // 更新所有购物车商品的选中状态
        for (Cart cart : cartList) {
            cart.setChecked(checked);
            updateById(cart);
        }

        return Result.success();
    }

    @Override
    public Result<Integer> getCartCount(Long userId) {
        if (userId == null) {
            return Result.error("参数错误");
        }

        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, userId);
        long count = count(queryWrapper);

        return Result.success((int)count);
    }

    @Override
    public Result<List<Cart>> getUserCartItems(Long userId) {
        try {
            if (userId == null) {
                return Result.error("参数错误");
            }
            
            // 查询用户购物车
            LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Cart::getUserId, userId)
                  .orderByDesc(Cart::getCreateTime);
            
            List<Cart> cartItems = list(wrapper);
            
            // 获取商品详情
            for (Cart item : cartItems) {
                Product product = productService.getById(item.getProductId());
                if (product != null) {
                    item.setProduct(product);
                    item.setPrice(product.getPrice());  // 设置价格
                }
            }
            
            return Result.success(cartItems);
        } catch (Exception e) {
            log.error("获取用户购物车失败: userId={}", userId, e);
            return Result.error("获取失败，请重试");
        }
    }
    
    @Override
    public Result<Boolean> updateCartItemQuantity(Long cartItemId, Integer quantity, Long userId) {
        try {
            if (cartItemId == null || quantity == null || quantity <= 0 || userId == null) {
                return Result.error("参数错误");
            }
            
            // 查询购物车记录
            LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Cart::getId, cartItemId)
                  .eq(Cart::getUserId, userId);
            
            Cart cart = getOne(wrapper);
            if (cart == null) {
                return Result.error("购物车商品不存在");
            }
            
            // 查询商品信息
            Product product = productService.getById(cart.getProductId());
            if (product == null) {
                return Result.error("商品不存在");
            }
            
            // 检查库存
            if (product.getStock() < quantity) {
                return Result.error("库存不足");
            }
            
            // 更新数量
            cart.setQuantity(quantity);
            boolean success = updateById(cart);
            
            return Result.success(success);
        } catch (Exception e) {
            log.error("更新购物车商品数量失败: cartItemId={}, quantity={}, userId={}", cartItemId, quantity, userId, e);
            return Result.error("更新失败，请重试");
        }
    }
    
    @Override
    public Result<Boolean> removeCartItem(Long cartItemId, Long userId) {
        try {
            if (cartItemId == null || userId == null) {
                return Result.error("参数错误");
            }
            
            // 查询购物车记录
            LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Cart::getId, cartItemId)
                  .eq(Cart::getUserId, userId);
            
            Cart cart = getOne(wrapper);
            if (cart == null) {
                return Result.error("购物车商品不存在");
            }
            
            // 删除购物车记录
            boolean success = removeById(cartItemId);
            
            return Result.success(success);
        } catch (Exception e) {
            log.error("删除购物车商品失败: cartItemId={}, userId={}", cartItemId, userId, e);
            return Result.error("删除失败，请重试");
        }
    }
    
    @Override
    public Result<Boolean> clearCart(Long userId) {
        try {
            if (userId == null) {
                return Result.error("参数错误");
            }
            
            // 查询用户购物车所有商品
            LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Cart::getUserId, userId);
            
            List<Cart> cartItems = list(wrapper);
            
            // 删除所有购物车记录
            for (Cart item : cartItems) {
                removeById(item.getId());
            }
            
            return Result.success(true);
        } catch (Exception e) {
            log.error("清空购物车失败: userId={}", userId, e);
            return Result.error("清空失败，请重试");
        }
    }
} 